import sys
import os
import zipfile
import tempfile
import subprocess
import secrets
import string
import hashlib
import hmac
import struct
from typing import List, Dict, Tuple, Optional

from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
    QPushButton, QLabel, QFileDialog, QLineEdit, QProgressBar, QMessageBox,
    QGroupBox, QSpinBox, QCheckBox, QComboBox, QInputDialog, QScrollArea,
    QSizePolicy, QFrame, QTabWidget
)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QSize
from PyQt5.QtGui import QFont, QPalette, QIcon, QPixmap

class FileEncryptor:
    """文件加密解密核心类"""
    def __init__(self):
        self.block_size = 16
        self.version = "SFv1.0"
        self.version_bytes = self.version.encode('utf-8')
    
    def derive_key(self, password: str, salt: bytes) -> bytes:
        # 简化的PBKDF2实现
        key = b''
        iterations = 100000
        key_length = 32
        
        for i in range(1, 3): 
            block = hmac.new(
                password.encode('utf-8'),
                salt + struct.pack('>I', i),
                hashlib.sha256
            ).digest()
            
            for _ in range(iterations // 1000):
                block = hmac.new(password.encode('utf-8'), block, hashlib.sha256).digest()
            
            key += block
        
        return key[:key_length]
    
    def encrypt_file(self, input_path: str, output_path: str, password: str, compress: bool = False) -> bool:
        """加密文件"""
        try:
            salt = os.urandom(16)
            iv = os.urandom(16)
            
            key = self.derive_key(password, salt)
            
            with open(input_path, 'rb') as f_in:
                plaintext = f_in.read()
            ciphertext = self._simple_encrypt(plaintext, key, iv)
            hash_value = hashlib.sha256(plaintext).digest()
            
            with open(output_path, 'wb') as f_out:
                f_out.write(self.version_bytes)
                f_out.write(salt)
                f_out.write(iv)
                f_out.write(hash_value)
                f_out.write(ciphertext)
            
            return True
        except Exception as e:
            print(f"加密错误: {str(e)}")
            return False
    
    def decrypt_file(self, input_path: str, output_path: str, password: str) -> bool:
        """解密文件"""
        try:
            with open(input_path, 'rb') as f_in:
                version = f_in.read(len(self.version_bytes))
                if version != self.version_bytes:
                    return False
                
                salt = f_in.read(16)
                iv = f_in.read(16)
                stored_hash = f_in.read(32)
                ciphertext = f_in.read()
            
            key = self.derive_key(password, salt)
            plaintext = self._simple_decrypt(ciphertext, key, iv)
            
            current_hash = hashlib.sha256(plaintext).digest()
            if current_hash != stored_hash:
                return False
            
            with open(output_path, 'wb') as f_out:
                f_out.write(plaintext)
            
            return True
        except Exception as e:
            print(f"解密错误: {str(e)}")
            return False
    
    def _simple_encrypt(self, data: bytes, key: bytes, iv: bytes) -> bytes:
        encrypted = bytearray()
        key_len = len(key)
        for i, byte in enumerate(data):
            encrypted.append(byte ^ key[i % key_len] ^ iv[i % len(iv)])
        return bytes(encrypted)
    
    def _simple_decrypt(self, data: bytes, key: bytes, iv: bytes) -> bytes:
        """简化的解密函数"""
        return self._simple_encrypt(data, key, iv)  # XOR加密解密相同

class PasswordGenerator:
    """密码生成器"""
    def __init__(self):
        self.character_sets = {
            'lowercase': string.ascii_lowercase,
            'uppercase': string.ascii_uppercase,
            'digits': string.digits,
            'special': '!@#$%^&*()_+-=[]{}|;:,.<>?'
        }
    
    def generate_password(self, length: int = 12, use_upper: bool = True, 
                         use_digits: bool = True, use_special: bool = True) -> str:
        """生成随机密码"""
        charset = self.character_sets['lowercase']
        if use_upper:
            charset += self.character_sets['uppercase']
        if use_digits:
            charset += self.character_sets['digits']
        if use_special:
            charset += self.character_sets['special']
        
        return ''.join(secrets.choice(charset) for _ in range(length))
    
    def generate_memorable_password(self) -> str:
        """生成易记密码"""
        words = ['apple', 'ball', 'cat', 'dog', 'eagle', 'fish', 'goat', 'house']
        numbers = ['123', '456', '789', '100', '202']
        separators = ['!', '@', '#', '$', '%']
        
        word1 = secrets.choice(words).capitalize()
        word2 = secrets.choice(words)
        number = secrets.choice(numbers)
        separator = secrets.choice(separators)
        
        return f"{word1}{number}{separator}{word2}"

class PasswordStrengthChecker:
    """密码强度检查器"""
    def check_strength(self, password: str) -> Dict:
        """检查密码强度"""
        score = 0
        feedback = []
        
        # 长度检查
        length = len(password)
        if length >= 12:
            score += 3
        elif length >= 8:
            score += 2
            feedback.append("建议密码长度至少12位")
        else:
            score += 1
            feedback.append("密码过短，建议至少8位")
        
        # 字符种类检查
        criteria = {
            '大写字母': any(c.isupper() for c in password),
            '小写字母': any(c.islower() for c in password),
            '数字': any(c.isdigit() for c in password),
            '特殊字符': any(c in '!@#$%^&*()_+-=[]{}|;:,.<>?' for c in password)
        }
        
        criteria_met = sum(criteria.values())
        score += criteria_met
        
        for name, met in criteria.items():
            if not met:
                feedback.append(f"建议包含{name}")
        
        # 确定强度等级
        if score >= 7:
            strength = "强"
        elif score >= 4:
            strength = "中"
        else:
            strength = "弱"
        
        return {'score': score, 'strength': strength, 'feedback': feedback}

class MobileEncryptionApp(QMainWindow):
    """为移动设备优化的加密应用"""
    
    def __init__(self):
        super().__init__()
        self.encryptor = FileEncryptor()
        self.password_generator = PasswordGenerator()
        self.strength_checker = PasswordStrengthChecker()
        self.current_file = ""
        
        self.setup_ui()
        self.apply_mobile_styles()
    
    def setup_ui(self):
        """设置移动设备优化的UI"""
        self.setWindowTitle("流星加密王")
        self.setMinimumSize(360, 640)
        
        # 创建中央滚动区域
        central_widget = QWidget()
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setWidget(central_widget)
        self.setCentralWidget(scroll_area)
        
        # 主布局
        main_layout = QVBoxLayout()
        central_widget.setLayout(main_layout)
        
        # 应用标题
        title_label = QLabel("🔐 流星加密王")
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet("""
            QLabel {
                font-size: 24px;
                font-weight: bold;
                color: #2c3e50;
                padding: 20px;
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #3498db, stop:1 #2980b9);
                color: white;
                border-radius: 15px;
                margin: 5px;
            }
        """)
        main_layout.addWidget(title_label)
        self.tab_widget = QTabWidget()
        main_layout.addWidget(self.tab_widget)
        self.setup_file_tab()
        self.setup_password_tab()
        self.setup_batch_tab()
        self.setup_status_section(main_layout)
    
    def setup_file_tab(self):
        """设置文件操作标签页"""
        file_tab = QWidget()
        layout = QVBoxLayout()
        file_tab.setLayout(layout)
        
        # 文件选择区域
        file_group = QGroupBox("📁 文件选择")
        file_layout = QVBoxLayout()
        
        self.file_label = QLabel("未选择文件")
        self.file_label.setAlignment(Qt.AlignCenter)
        self.file_label.setStyleSheet("""
            QLabel {
                border: 2px dashed #bdc3c7;
                border-radius: 10px;
                padding: 15px;
                background-color: #ecf0f1;
                min-height: 60px;
                font-size: 14px;
            }
        """)
        self.file_label.setWordWrap(True)
        
        self.file_btn = QPushButton("选择文件")
        self.file_btn.setMinimumHeight(60)
        self.file_btn.clicked.connect(self.select_file)
        
        file_layout.addWidget(self.file_label)
        file_layout.addWidget(self.file_btn)
        file_group.setLayout(file_layout)
        
        # 操作选项
        options_group = QGroupBox("⚙️ 选项设置")
        options_layout = QGridLayout()
        
        self.compress_check = QCheckBox("加密前压缩文件")
        self.compress_check.setChecked(True)
        
        self.overwrite_check = QCheckBox("覆盖原文件")
        self.overwrite_check.setChecked(False)
        
        options_layout.addWidget(self.compress_check, 0, 0)
        options_layout.addWidget(self.overwrite_check, 0, 1)
        options_group.setLayout(options_layout)
        
        # 操作按钮
        operation_group = QGroupBox("🛡️ 文件操作")
        operation_layout = QVBoxLayout()
        
        self.encrypt_btn = QPushButton("🔒 加密文件")
        self.encrypt_btn.setMinimumHeight(70)
        self.encrypt_btn.clicked.connect(self.encrypt_file)
        
        self.decrypt_btn = QPushButton("🔓 解密文件")
        self.decrypt_btn.setMinimumHeight(70)
        self.decrypt_btn.clicked.connect(self.decrypt_file)
        
        operation_layout.addWidget(self.encrypt_btn)
        operation_layout.addWidget(self.decrypt_btn)
        operation_group.setLayout(operation_layout)
        
        # 添加到标签页
        layout.addWidget(file_group)
        layout.addWidget(options_group)
        layout.addWidget(operation_group)
        layout.addStretch()
        
        self.tab_widget.addTab(file_tab, "文件加密")
    
    def setup_password_tab(self):
        """设置密码管理标签页"""
        password_tab = QWidget()
        layout = QVBoxLayout()
        password_tab.setLayout(layout)
        
        # 密码输入区域
        input_group = QGroupBox("🔑 密码输入")
        input_layout = QGridLayout()
        
        input_layout.addWidget(QLabel("密码:"), 0, 0)
        self.pwd_input = QLineEdit()
        self.pwd_input.setEchoMode(QLineEdit.Password)
        self.pwd_input.setMinimumHeight(50)
        self.pwd_input.textChanged.connect(self.check_password_strength)
        input_layout.addWidget(self.pwd_input, 0, 1)
        
        self.show_pwd_check = QCheckBox("显示密码")
        self.show_pwd_check.stateChanged.connect(self.toggle_password_visibility)
        input_layout.addWidget(self.show_pwd_check, 1, 0, 1, 2)
        
        input_group.setLayout(input_layout)
        
        # 密码生成选项
        generate_group = QGroupBox("🎲 密码生成")
        generate_layout = QGridLayout()
        
        generate_layout.addWidget(QLabel("长度:"), 0, 0)
        self.length_spin = QSpinBox()
        self.length_spin.setRange(8, 32)
        self.length_spin.setValue(12)
        self.length_spin.setMinimumHeight(45)
        generate_layout.addWidget(self.length_spin, 0, 1)
        
        self.upper_check = QCheckBox("大写字母")
        self.upper_check.setChecked(True)
        generate_layout.addWidget(self.upper_check, 1, 0)
        
        self.digit_check = QCheckBox("数字")
        self.digit_check.setChecked(True)
        generate_layout.addWidget(self.digit_check, 1, 1)
        
        self.special_check = QCheckBox("特殊字符")
        self.special_check.setChecked(True)
        generate_layout.addWidget(self.special_check, 2, 0)
        
        generate_group.setLayout(generate_layout)
        
        # 生成按钮
        button_layout = QHBoxLayout()
        
        self.generate_btn = QPushButton("生成随机密码")
        self.generate_btn.setMinimumHeight(55)
        self.generate_btn.clicked.connect(self.generate_password)
        
        self.memorable_btn = QPushButton("生成易记密码")
        self.memorable_btn.setMinimumHeight(55)
        self.memorable_btn.clicked.connect(self.generate_memorable_password)
        
        button_layout.addWidget(self.generate_btn)
        button_layout.addWidget(self.memorable_btn)
        
        # 密码强度显示
        strength_group = QGroupBox("📊 密码强度")
        strength_layout = QVBoxLayout()
        
        self.strength_label = QLabel("强度: 未检查")
        self.strength_label.setAlignment(Qt.AlignCenter)
        self.strength_label.setMinimumHeight(40)
        
        strength_layout.addWidget(self.strength_label)
        strength_group.setLayout(strength_layout)
        
        # 添加到标签页
        layout.addWidget(input_group)
        layout.addWidget(generate_group)
        layout.addLayout(button_layout)
        layout.addWidget(strength_group)
        layout.addStretch()
        
        self.tab_widget.addTab(password_tab, "密码管理")
    
    def setup_batch_tab(self):
        """设置批量处理标签页"""
        batch_tab = QWidget()
        layout = QVBoxLayout()
        batch_tab.setLayout(layout)
        
        # 文件夹选择
        folder_group = QGroupBox("📂 批量处理")
        folder_layout = QVBoxLayout()
        
        self.folder_label = QLabel("未选择文件夹")
        self.folder_label.setAlignment(Qt.AlignCenter)
        self.folder_label.setStyleSheet("""
            QLabel {
                border: 2px dashed #bdc3c7;
                border-radius: 10px;
                padding: 15px;
                background-color: #ecf0f1;
                min-height: 60px;
                font-size: 14px;
            }
        """)
        self.folder_label.setWordWrap(True)
        
        self.folder_btn = QPushButton("选择文件夹")
        self.folder_btn.setMinimumHeight(60)
        self.folder_btn.clicked.connect(self.select_folder)
        
        folder_layout.addWidget(self.folder_label)
        folder_layout.addWidget(self.folder_btn)
        folder_group.setLayout(folder_layout)
        
        # 批量操作选项
        batch_options_group = QGroupBox("⚙️ 批量设置")
        batch_options_layout = QVBoxLayout()
        
        self.batch_mode_combo = QComboBox()
        self.batch_mode_combo.addItems(["加密所有文件", "解密所有文件"])
        
        self.include_subdirs = QCheckBox("包含子文件夹")
        self.include_subdirs.setChecked(True)
        
        batch_options_layout.addWidget(QLabel("操作模式:"))
        batch_options_layout.addWidget(self.batch_mode_combo)
        batch_options_layout.addWidget(self.include_subdirs)
        batch_options_group.setLayout(batch_options_layout)
        
        # 批量操作按钮
        batch_btn_layout = QHBoxLayout()
        
        self.batch_process_btn = QPushButton("开始批量处理")
        self.batch_process_btn.setMinimumHeight(70)
        self.batch_process_btn.clicked.connect(self.batch_process)
        self.batch_process_btn.setStyleSheet("background-color: #e67e22; color: white;")
        
        batch_btn_layout.addWidget(self.batch_process_btn)
        
        # 添加到标签页
        layout.addWidget(folder_group)
        layout.addWidget(batch_options_group)
        layout.addLayout(batch_btn_layout)
        layout.addStretch()
        
        self.tab_widget.addTab(batch_tab, "批量处理")
    
    def setup_status_section(self, main_layout):
        """设置状态显示区域"""
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        self.progress_bar.setMinimumHeight(30)
        self.progress_bar.setVisible(False)
        
        # 状态标签
        self.status_label = QLabel("就绪")
        self.status_label.setAlignment(Qt.AlignCenter)
        self.status_label.setStyleSheet("""
            QLabel {
                background-color: #34495e;
                color: white;
                padding: 12px;
                border-radius: 10px;
                font-size: 14px;
                min-height: 20px;
            }
        """)
        self.status_label.setWordWrap(True)
        
        main_layout.addWidget(self.progress_bar)
        main_layout.addWidget(self.status_label)
    
    def apply_mobile_styles(self):
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f5f6fa;
            }
            QTabWidget::pane {
                border: 1px solid #c4c4c4;
                border-radius: 10px;
                background-color: white;
                margin: 5px;
            }
            QTabBar::tab {
                background-color: #ecf0f1;
                border: 1px solid #bdc3c7;
                padding: 12px 20px;
                margin: 2px;
                border-top-left-radius: 8px;
                border-top-right-radius: 8px;
                font-size: 14px;
                min-width: 100px;
            }
            QTabBar::tab:selected {
                background-color: #3498db;
                color: white;
                border-bottom-color: #3498db;
            }
            QGroupBox {
                font-weight: bold;
                font-size: 16px;
                border: 2px solid #ddd;
                border-radius: 12px;
                margin-top: 10px;
                padding-top: 15px;
                background-color: white;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 15px;
                padding: 0 10px 0 10px;
                color: #2c3e50;
            }
            QPushButton {
                min-height: 50px;
                border-radius: 10px;
                font-size: 16px;
                font-weight: bold;
                margin: 5px;
                background-color: #3498db;
                color: white;
                border: none;
            }
            QPushButton:pressed {
                background-color: #2980b9;
            }
            QPushButton:disabled {
                background-color: #bdc3c7;
                color: #7f8c8d;
            }
            QLineEdit, QSpinBox {
                min-height: 45px;
                font-size: 16px;
                padding: 10px;
                border: 2px solid #bdc3c7;
                border-radius: 8px;
                background-color: white;
            }
            QCheckBox {
                spacing: 10px;
                min-height: 40px;
                font-size: 14px;
            }
            QCheckBox::indicator {
                width: 25px;
                height: 25px;
            }
            QComboBox {
                min-height: 45px;
                font-size: 16px;
                padding: 10px;
                border: 2px solid #bdc3c7;
                border-radius: 8px;
                background-color: white;
            }
            QProgressBar {
                min-height: 30px;
                border-radius: 5px;
                text-align: center;
                font-size: 14px;
                border: 1px solid #bdc3c7;
            }
            QProgressBar::chunk {
                background-color: #27ae60;
                border-radius: 5px;
            }
        """)
    
    def select_file(self):
        """选择文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择文件", "", 
            "所有文件 (*.*);;文本文件 (*.txt);;文档文件 (*.docx *.pdf);;图片文件 (*.jpg *.png)"
        )
        if file_path:
            self.current_file = file_path
            self.file_label.setText(f"已选择: {os.path.basename(file_path)}")
            self.status_label.setText(f"已选择文件: {os.path.basename(file_path)}")
    
    def select_folder(self):
        """选择文件夹"""
        folder_path = QFileDialog.getExistingDirectory(self, "选择文件夹")
        if folder_path:
            self.folder_label.setText(f"已选择: {os.path.basename(folder_path)}")
            self.status_label.setText(f"已选择文件夹: {os.path.basename(folder_path)}")
    
    def toggle_password_visibility(self, state):
        """切换密码显示"""
        if state == Qt.Checked:
            self.pwd_input.setEchoMode(QLineEdit.Normal)
        else:
            self.pwd_input.setEchoMode(QLineEdit.Password)
    
    def generate_password(self):
        """生成随机密码"""
        length = self.length_spin.value()
        use_upper = self.upper_check.isChecked()
        use_digits = self.digit_check.isChecked()
        use_special = self.special_check.isChecked()
        
        password = self.password_generator.generate_password(length, use_upper, use_digits, use_special)
        self.pwd_input.setText(password)
        self.check_password_strength(password)
    
    def generate_memorable_password(self):
        """生成易记密码"""
        password = self.password_generator.generate_memorable_password()
        self.pwd_input.setText(password)
        self.check_password_strength(password)
    
    def check_password_strength(self, password=None):
        """检查密码强度"""
        if password is None:
            password = self.pwd_input.text()
        
        if not password:
            self.strength_label.setText("强度: 未输入密码")
            self.strength_label.setStyleSheet("color: #95a5a6;")
            return
        
        result = self.strength_checker.check_strength(password)
        
        color_map = {"弱": "#e74c3c", "中": "#f39c12", "强": "#27ae60"}
        color = color_map.get(result['strength'], "#95a5a6")
        
        self.strength_label.setText(
            f"强度: {result['strength']} (得分: {result['score']}/10)"
        )
        self.strength_label.setStyleSheet(f"color: {color}; font-weight: bold;")
        
        if result['feedback']:
            self.status_label.setText(f"建议: {', '.join(result['feedback'])}")
    
    def encrypt_file(self):
        """加密文件"""
        if not self.current_file:
            QMessageBox.warning(self, "警告", "请先选择要加密的文件")
            return
        
        password = self.pwd_input.text()
        if not password:
            QMessageBox.warning(self, "警告", "请输入加密密码")
            return
        
        # 检查密码强度
        strength_result = self.strength_checker.check_strength(password)
        if strength_result['strength'] == "弱":
            reply = QMessageBox.question(
                self, "密码强度警告",
                "您使用的密码强度较弱，容易被破解。是否继续使用此密码？",
                QMessageBox.Yes | QMessageBox.No
            )
            if reply == QMessageBox.No:
                return
        
        # 设置输出路径
        if self.overwrite_check.isChecked():
            output_path = self.current_file + ".sf"
        else:
            output_path, _ = QFileDialog.getSaveFileName(
                self, "保存加密文件", 
                os.path.splitext(self.current_file)[0] + ".sf"
            )
            if not output_path:
                return
        
        # 执行加密
        self.status_label.setText("加密中...")
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(30)
        
        QApplication.processEvents()  # 更新UI
        
        success = self.encryptor.encrypt_file(
            self.current_file, output_path, password, self.compress_check.isChecked()
        )
        
        self.progress_bar.setValue(100)
        
        if success:
            QMessageBox.information(self, "成功", f"文件加密成功!\n已保存为: {output_path}")
            self.status_label.setText("加密完成")
        else:
            QMessageBox.critical(self, "错误", "文件加密失败")
            self.status_label.setText("加密失败")
        
        self.progress_bar.setVisible(False)
    
    def decrypt_file(self):
        """解密文件"""
        if not self.current_file:
            QMessageBox.warning(self, "警告", "请先选择要解密的文件")
            return
        
        password = self.pwd_input.text()
        if not password:
            QMessageBox.warning(self, "警告", "请输入解密密码")
            return
        
        # 设置输出路径
        if self.overwrite_check.isChecked():
            output_path = self.current_file.replace('.sf', '')
        else:
            default_name = os.path.splitext(self.current_file)[0]
            if default_name.endswith('.sf'):
                default_name = default_name[:-10]  # 移除.encrypted后缀
            
            output_path, _ = QFileDialog.getSaveFileName(
                self, "保存解密文件", default_name
            )
            if not output_path:
                return
        
        # 执行解密
        self.status_label.setText("解密中...")
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(30)
        
        QApplication.processEvents()  # 更新UI
        
        success = self.encryptor.decrypt_file(self.current_file, output_path, password)
        
        self.progress_bar.setValue(100)
        
        if success:
            QMessageBox.information(self, "成功", f"文件解密成功!\n已保存为: {output_path}")
            self.status_label.setText("解密完成")
        else:
            QMessageBox.critical(self, "错误", "文件解密失败，请检查密码是否正确")
            self.status_label.setText("解密失败")
        
        self.progress_bar.setVisible(False)
    
    def batch_process(self):
        """批量处理文件夹"""
        folder_path = os.path.dirname(self.current_file) if self.current_file else ""
        if not folder_path:
            folder_path = QFileDialog.getExistingDirectory(self, "选择文件夹")
            if not folder_path:
                return
        
        password = self.pwd_input.text()
        if not password:
            QMessageBox.warning(self, "警告", "请输入密码")
            return
        
        mode = self.batch_mode_combo.currentText()
        include_subdirs = self.include_subdirs.isChecked()
        
        # 收集文件
        files = []
        if include_subdirs:
            for root, _, filenames in os.walk(folder_path):
                for filename in filenames:
                    if mode == "加密所有文件" and not filename.endswith('.sf'):
                        files.append(os.path.join(root, filename))
                    elif mode == "解密所有文件" and filename.endswith('.sf'):
                        files.append(os.path.join(root, filename))
        else:
            for filename in os.listdir(folder_path):
                filepath = os.path.join(folder_path, filename)
                if os.path.isfile(filepath):
                    if mode == "加密所有文件" and not filename.endswith('.sf'):
                        files.append(filepath)
                    elif mode == "解密所有文件" and filename.endswith('.sf'):
                        files.append(filepath)
        
        if not files:
            QMessageBox.information(self, "信息", "没有找到符合条件的文件")
            return
        
        # 创建进度对话框
        progress_dialog = QFileDialog(
            f"正在处理 {len(files)} 个文件...", "取消", 0, len(files), self
        )
        progress_dialog.setWindowTitle("批量处理")
        progress_dialog.setWindowModality(Qt.WindowModal)
        progress_dialog.show()
        
        # 处理文件
        success_count = 0
        for i, file_path in enumerate(files):
            if progress_dialog.wasCanceled():
                break
                
            progress_dialog.setValue(i)
            progress_dialog.setLabelText(f"正在处理: {os.path.basename(file_path)}")
            QApplication.processEvents()
            
            try:
                if mode == "加密所有文件":
                    output_path = file_path + ".sf"
                    success = self.encryptor.encrypt_file(
                        file_path, output_path, password, self.compress_check.isChecked()
                    )
                else:
                    output_path = file_path.replace('.sf', '')
                    success = self.encryptor.decrypt_file(file_path, output_path, password)
                
                if success:
                    success_count += 1
            except Exception as e:
                print(f"处理文件 {file_path} 时出错: {str(e)}")
        
        progress_dialog.close()
        
        QMessageBox.information(
            self, "完成", 
            f"批量处理完成!\n成功: {success_count}个, 失败: {len(files) - success_count}个"
        )
        self.status_label.setText(f"批量处理完成: {success_count}/{len(files)} 成功")

def main():
    """主函数"""
    app = QApplication(sys.argv)
    app.setApplicationName("安全文件加密工具")
    app.setApplicationVersion("1.0")
    app.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    app.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
    
    window = MobileEncryptionApp()
    window.show()
    
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()